package com.zenithmind.chat.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zenithmind.chat.mapper.ChatMessageStatisticsMapper;
import com.zenithmind.chat.pojo.entity.ChatMessageStatistics;
import com.zenithmind.chat.pojo.vo.ChatMessageStatisticsVO;
import com.zenithmind.chat.service.ChatMessageStatisticsService;
import com.zenithmind.common.exception.BusinessException;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 消息统计服务实现类 - 遵循单一职责原则
 * 只负责消息统计的业务逻辑处理
 * 
 * @author ZenithMind Team
 * @since 2025-01-09
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class ChatMessageStatisticsServiceImpl extends ServiceImpl<ChatMessageStatisticsMapper, ChatMessageStatistics> 
        implements ChatMessageStatisticsService {

    @Override
    @Transactional(rollbackFor = Exception.class)
    public String createMessageStatistics(String messageId, String userId, String groupId) {
        if (messageId == null || messageId.trim().isEmpty()) {
            throw new BusinessException("消息ID不能为空");
        }
        
        // 检查是否已存在统计记录
        LambdaQueryWrapper<ChatMessageStatistics> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(ChatMessageStatistics::getMessageId, messageId)
                   .eq(ChatMessageStatistics::getIsDeleted, 0);
        
        ChatMessageStatistics existing = getOne(queryWrapper);
        if (existing != null) {
            return existing.getId();
        }
        
        ChatMessageStatistics statistics = new ChatMessageStatistics();
        statistics.setMessageId(messageId);
        statistics.setUserId(userId);
        statistics.setGroupId(groupId);
        statistics.setLikeCount(0);
        statistics.setReplyCount(0);
        statistics.setForwardCount(0);
        statistics.setReadCount(0);
        statistics.setShareCount(0);
        statistics.setFavoriteCount(0);
        statistics.setReportCount(0);
        statistics.setCreateTime(LocalDateTime.now());
        statistics.setUpdateTime(LocalDateTime.now());
        
        save(statistics);
        
        log.info("创建消息统计记录成功，消息ID: {}, 统计ID: {}", messageId, statistics.getId());
        
        return statistics.getId();
    }

    @Override
    public ChatMessageStatisticsVO getStatisticsByMessageId(String messageId) {
        if (messageId == null || messageId.trim().isEmpty()) {
            throw new BusinessException("消息ID不能为空");
        }
        
        LambdaQueryWrapper<ChatMessageStatistics> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(ChatMessageStatistics::getMessageId, messageId)
                   .eq(ChatMessageStatistics::getIsDeleted, 0);
        
        ChatMessageStatistics statistics = getOne(queryWrapper);
        if (statistics == null) {
            // 如果不存在统计记录，创建一个默认的
            createMessageStatistics(messageId, null, null);
            statistics = getOne(queryWrapper);
        }
        
        return convertToVO(statistics);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean incrementLikeCount(String messageId) {
        return updateCount(messageId, "like", 1);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean decrementLikeCount(String messageId) {
        return updateCount(messageId, "like", -1);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean incrementReplyCount(String messageId) {
        return updateCount(messageId, "reply", 1);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean decrementReplyCount(String messageId) {
        return updateCount(messageId, "reply", -1);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean incrementForwardCount(String messageId) {
        return updateCount(messageId, "forward", 1);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean incrementReadCount(String messageId) {
        return updateCount(messageId, "read", 1);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean batchIncrementReadCount(List<String> messageIds) {
        if (messageIds == null || messageIds.isEmpty()) {
            return true;
        }
        
        for (String messageId : messageIds) {
            incrementReadCount(messageId);
        }
        
        log.info("批量增加阅读数成功，消息数量: {}", messageIds.size());
        
        return true;
    }

    @Override
    public List<ChatMessageStatisticsVO> getUserMessageStatistics(String userId, LocalDateTime startTime, LocalDateTime endTime) {
        LambdaQueryWrapper<ChatMessageStatistics> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(ChatMessageStatistics::getUserId, userId)
                   .eq(ChatMessageStatistics::getIsDeleted, 0)
                   .orderByDesc(ChatMessageStatistics::getCreateTime);
        
        if (startTime != null) {
            queryWrapper.ge(ChatMessageStatistics::getCreateTime, startTime);
        }
        if (endTime != null) {
            queryWrapper.le(ChatMessageStatistics::getCreateTime, endTime);
        }
        
        List<ChatMessageStatistics> statisticsList = list(queryWrapper);
        return statisticsList.stream().map(this::convertToVO).collect(Collectors.toList());
    }

    @Override
    public List<ChatMessageStatisticsVO> getGroupMessageStatistics(String groupId, LocalDateTime startTime, LocalDateTime endTime) {
        LambdaQueryWrapper<ChatMessageStatistics> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(ChatMessageStatistics::getGroupId, groupId)
                   .eq(ChatMessageStatistics::getIsDeleted, 0)
                   .orderByDesc(ChatMessageStatistics::getCreateTime);
        
        if (startTime != null) {
            queryWrapper.ge(ChatMessageStatistics::getCreateTime, startTime);
        }
        if (endTime != null) {
            queryWrapper.le(ChatMessageStatistics::getCreateTime, endTime);
        }
        
        List<ChatMessageStatistics> statisticsList = list(queryWrapper);
        return statisticsList.stream().map(this::convertToVO).collect(Collectors.toList());
    }

    @Override
    public Long countUserMessages(String userId, LocalDateTime startTime, LocalDateTime endTime) {
        LambdaQueryWrapper<ChatMessageStatistics> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(ChatMessageStatistics::getUserId, userId)
                   .eq(ChatMessageStatistics::getIsDeleted, 0);
        
        if (startTime != null) {
            queryWrapper.ge(ChatMessageStatistics::getCreateTime, startTime);
        }
        if (endTime != null) {
            queryWrapper.le(ChatMessageStatistics::getCreateTime, endTime);
        }
        
        return count(queryWrapper);
    }

    @Override
    public Long countGroupMessages(String groupId, LocalDateTime startTime, LocalDateTime endTime) {
        LambdaQueryWrapper<ChatMessageStatistics> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(ChatMessageStatistics::getGroupId, groupId)
                   .eq(ChatMessageStatistics::getIsDeleted, 0);
        
        if (startTime != null) {
            queryWrapper.ge(ChatMessageStatistics::getCreateTime, startTime);
        }
        if (endTime != null) {
            queryWrapper.le(ChatMessageStatistics::getCreateTime, endTime);
        }
        
        return count(queryWrapper);
    }

    @Override
    public List<ChatMessageStatisticsVO> getPopularMessages(String groupId, String rankType, Integer limit, 
                                                           LocalDateTime startTime, LocalDateTime endTime) {
        LambdaQueryWrapper<ChatMessageStatistics> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(ChatMessageStatistics::getGroupId, groupId)
                   .eq(ChatMessageStatistics::getIsDeleted, 0);
        
        if (startTime != null) {
            queryWrapper.ge(ChatMessageStatistics::getCreateTime, startTime);
        }
        if (endTime != null) {
            queryWrapper.le(ChatMessageStatistics::getCreateTime, endTime);
        }
        
        // 根据排行类型排序
        switch (rankType.toLowerCase()) {
            case "like":
                queryWrapper.orderByDesc(ChatMessageStatistics::getLikeCount);
                break;
            case "reply":
                queryWrapper.orderByDesc(ChatMessageStatistics::getReplyCount);
                break;
            case "forward":
                queryWrapper.orderByDesc(ChatMessageStatistics::getForwardCount);
                break;
            case "read":
                queryWrapper.orderByDesc(ChatMessageStatistics::getReadCount);
                break;
            default:
                queryWrapper.orderByDesc(ChatMessageStatistics::getLikeCount);
        }
        
        queryWrapper.last("LIMIT " + (limit != null ? limit : 10));
        
        List<ChatMessageStatistics> statisticsList = list(queryWrapper);
        return statisticsList.stream().map(this::convertToVO).collect(Collectors.toList());
    }

    @Override
    public Object getUserActivityStatistics(String userId, LocalDateTime startTime, LocalDateTime endTime) {
        // TODO: 实现用户活跃度统计逻辑
        return new Object();
    }

    @Override
    public Object getGroupActivityStatistics(String groupId, LocalDateTime startTime, LocalDateTime endTime) {
        // TODO: 实现群组活跃度统计逻辑
        return new Object();
    }

    @Override
    public Object getMessageTypeDistribution(String groupId, LocalDateTime startTime, LocalDateTime endTime) {
        // TODO: 实现消息类型分布统计逻辑
        return new Object();
    }

    @Override
    public Object getMessageTimeDistribution(String groupId, LocalDateTime startTime, LocalDateTime endTime, String granularity) {
        // TODO: 实现消息时间分布统计逻辑
        return new Object();
    }

    @Override
    public Object getUserInteractionStatistics(String userId, LocalDateTime startTime, LocalDateTime endTime) {
        // TODO: 实现用户互动统计逻辑
        return new Object();
    }

    @Override
    public List<Object> getGroupMemberActivityRank(String groupId, String rankType, Integer limit, 
                                                  LocalDateTime startTime, LocalDateTime endTime) {
        // TODO: 实现群组成员活跃排行逻辑
        return List.of();
    }

    @Override
    public String generateStatisticsReport(String reportType, String targetId, LocalDateTime startTime, 
                                          LocalDateTime endTime, String format) {
        // TODO: 实现统计报告生成逻辑
        return "";
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Integer cleanupExpiredStatistics(Integer retentionDays) {
        LocalDateTime expireTime = LocalDateTime.now().minusDays(retentionDays);
        
        LambdaQueryWrapper<ChatMessageStatistics> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(ChatMessageStatistics::getIsDeleted, 0)
                   .lt(ChatMessageStatistics::getCreateTime, expireTime);
        
        List<ChatMessageStatistics> expiredStatistics = list(queryWrapper);
        
        for (ChatMessageStatistics statistics : expiredStatistics) {
            statistics.setIsDeleted(1);
            statistics.setUpdateTime(LocalDateTime.now());
            updateById(statistics);
        }
        
        log.info("清理过期统计数据完成，清理数量: {}", expiredStatistics.size());
        
        return expiredStatistics.size();
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean recalculateStatistics(String messageId) {
        // TODO: 实现重新计算统计数据逻辑
        return true;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean batchRecalculateStatistics(List<String> messageIds) {
        if (messageIds == null || messageIds.isEmpty()) {
            return true;
        }
        
        for (String messageId : messageIds) {
            recalculateStatistics(messageId);
        }
        
        return true;
    }

    @Override
    public String exportStatistics(String exportType, String targetId, LocalDateTime startTime, 
                                  LocalDateTime endTime, String format) {
        // TODO: 实现统计数据导出逻辑
        return "";
    }

    @Override
    public Object getRealTimeStatistics(String statisticsType, String targetId) {
        // TODO: 实现实时统计数据获取逻辑
        return new Object();
    }

    /**
     * 更新统计数量
     */
    private Boolean updateCount(String messageId, String countType, int delta) {
        if (messageId == null || messageId.trim().isEmpty()) {
            throw new BusinessException("消息ID不能为空");
        }
        
        LambdaQueryWrapper<ChatMessageStatistics> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(ChatMessageStatistics::getMessageId, messageId)
                   .eq(ChatMessageStatistics::getIsDeleted, 0);
        
        ChatMessageStatistics statistics = getOne(queryWrapper);
        if (statistics == null) {
            // 如果不存在统计记录，先创建
            createMessageStatistics(messageId, null, null);
            statistics = getOne(queryWrapper);
        }
        
        // 根据类型更新对应的计数
        switch (countType.toLowerCase()) {
            case "like":
                statistics.setLikeCount(Math.max(0, (statistics.getLikeCount() != null ? statistics.getLikeCount() : 0) + delta));
                break;
            case "reply":
                statistics.setReplyCount(Math.max(0, (statistics.getReplyCount() != null ? statistics.getReplyCount() : 0) + delta));
                break;
            case "forward":
                statistics.setForwardCount(Math.max(0, (statistics.getForwardCount() != null ? statistics.getForwardCount() : 0) + delta));
                break;
            case "read":
                statistics.setReadCount(Math.max(0, (statistics.getReadCount() != null ? statistics.getReadCount() : 0) + delta));
                break;
            case "share":
                statistics.setShareCount(Math.max(0, (statistics.getShareCount() != null ? statistics.getShareCount() : 0) + delta));
                break;
            case "favorite":
                statistics.setFavoriteCount(Math.max(0, (statistics.getFavoriteCount() != null ? statistics.getFavoriteCount() : 0) + delta));
                break;
            case "report":
                statistics.setReportCount(Math.max(0, (statistics.getReportCount() != null ? statistics.getReportCount() : 0) + delta));
                break;
            default:
                throw new BusinessException("不支持的统计类型: " + countType);
        }
        
        statistics.setUpdateTime(LocalDateTime.now());
        
        boolean result = updateById(statistics);
        
        if (result) {
            log.debug("更新消息统计成功，消息ID: {}, 类型: {}, 变化: {}", messageId, countType, delta);
        }
        
        return result;
    }

    /**
     * 转换为VO
     */
    private ChatMessageStatisticsVO convertToVO(ChatMessageStatistics statistics) {
        ChatMessageStatisticsVO vo = new ChatMessageStatisticsVO();
        vo.setId(statistics.getId());
        vo.setMessageId(statistics.getMessageId());
        vo.setUserId(statistics.getUserId());
        vo.setGroupId(statistics.getGroupId());
        vo.setLikeCount(statistics.getLikeCount());
        vo.setReplyCount(statistics.getReplyCount());
        vo.setForwardCount(statistics.getForwardCount());
        vo.setReadCount(statistics.getReadCount());
        vo.setShareCount(statistics.getShareCount());
        vo.setFavoriteCount(statistics.getFavoriteCount());
        vo.setReportCount(statistics.getReportCount());
        vo.setCreateTime(statistics.getCreateTime());
        vo.setUpdateTime(statistics.getUpdateTime());
        return vo;
    }
}
